/**
 * Listening to routes alone would waste rendering performance. Use the publish-subscribe model for distribution management
 * 如果是各组件单独监听路由会浪费渲染性能。使用发布订阅模式统一去进行分发管理。
 */
import mitt, { type Handler } from "mitt";
import type { RouteLocationNormalized } from "vue-router";

const emitter = mitt();

const key = Symbol("ROUTE_CHANGE");

let latestRoute: RouteLocationNormalized;

/**在全局入口守卫会触发这个函数，告诉路由发生变化 */
export function setRouteEmitter(to: RouteLocationNormalized) {
  emitter.emit(key, to);
  latestRoute = to;
}

/**给 路由改变 事件添加回调函数 */
export function listenerRouteChange(
  handler: (route: RouteLocationNormalized) => void,
  immediate = true
) {
  emitter.on(key, handler as Handler);
  if (immediate && latestRoute) {
    handler(latestRoute);
  }
}

export function removeRouteListener() {
  emitter.off(key);
}
